//
//  LZMapViewController.m
//  laziz_Consumer
//
//  Created by XMac on 16/11/3.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMapViewController.h"
#import "Masonry.h"
#import "CustomAnnotationView.h"
#import "SMCalloutView.h"
#import "LZMapModel.h"
#import "LZAlertView.h"
#import "UIViewController+NavigationItemSetting.h"
#import "LZRestaurantAuthModel.h"
#import "CityManager.h"
#import "CitysModel.h"
#import "extobjc.h"

@import GoogleMaps;

@interface LZMapViewController ()<GMSMapViewDelegate>

@property(nonatomic , strong) SMCalloutView *calloutView;
@property(nonatomic , strong) UIView *emptyCalloutView;
@property (strong, nonatomic) UIButton *nav_left_back;

@property (strong, nonatomic) UIButton   *confirmBtn;
@property (strong, nonatomic) GMSMapView *gmsMapView;
@property (strong, nonatomic) GMSMarker  *chooseMarker;
@property (assign, nonatomic) CGFloat chooseLat;
@property (assign, nonatomic) CGFloat chooseLon;
@end

@implementation LZMapViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"地图页面";
    
    self.title = LZLocalizedString(@"restaurant_address", nil);
    
    
    if (self.authModel) {
        [self configureNavBar];
        [self configureUIForChooseMarker];
    }else{
        [self configUI];
    }
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    DLog(@"dealloc");
}


#pragma
#pragma mark Private method
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString:@"myLocation"]) {
        CLLocation *location = [object myLocation];
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude zoom:10];
        
        self.gmsMapView.camera = camera;
        
        //定位完自己,及时移除,不然会影响缩放
        [self.gmsMapView removeObserver:self forKeyPath:@"myLocation"];
    }
}


/**
 认证商家选择地图标记是初始化此方法
 */
-(void)configureUIForChooseMarker
{
    self.gmsMapView = [[GMSMapView alloc] initWithFrame:self.view.frame];
    [self.gmsMapView addObserver:self forKeyPath:@"myLocation" options:NSKeyValueObservingOptionNew context:nil];
    
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:self.gmsMapView.myLocation.coordinate.latitude longitude:self.gmsMapView.myLocation.coordinate.longitude zoom:10];
    
    self.gmsMapView.camera = camera;
    
    self.gmsMapView.delegate = self;
    
    self.gmsMapView.myLocationEnabled = YES;
    
    [self.view addSubview:self.gmsMapView];
    
    self.chooseMarker = [GMSMarker new];
    self.chooseMarker.icon = [UIImage imageNamed:@"map_location_icon_select"];
    if (self.authModel.mapLocationLongitude > 0) {
        self.chooseMarker.position = CLLocationCoordinate2DMake(self.authModel.mapLocationLatitude, self.authModel.mapLocationLongitude);
        self.chooseMarker.map = self.gmsMapView;
    }
    
}

- (void)configureNavBar
{
    self.confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.confirmBtn.frame = CGRectMake(0, 0, 60, 40);
    self.confirmBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.confirmBtn setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
    [self.confirmBtn setTitle:LZLocalizedString(@"submit_min", nil) forState:UIControlStateNormal];
    [self.confirmBtn addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    [self navigationItemSetting:@[self.confirmBtn] type:NAVIGATIONITEMSETTING_RIGHT];
}

- (NSString *)checkNullWithStr:(NSString *)str
{
    if ((!str || (NSNull *)str == [NSNull null]))  {
        return @"";
    }
    return str;
}
- (void)confirmAction
{
    @weakify(self);
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:NO];
    GMSGeocoder *geocoder = [[GMSGeocoder alloc] init];
    [geocoder reverseGeocodeCoordinate:CLLocationCoordinate2DMake(self.chooseLat, self.chooseLon)  completionHandler:^(GMSReverseGeocodeResponse * address, NSError * error) {
       @strongify(self);
       NSString *addressStr = [NSString stringWithFormat:@"%@%@%@",[self checkNullWithStr:address.firstResult.administrativeArea],[self checkNullWithStr:address.firstResult.locality],[self checkNullWithStr:address.firstResult.thoroughfare]];
       self.authModel.mapLocationLongitude = self.chooseLon;
       self.authModel.mapLocationLatitude = self.chooseLat;
       self.authModel.mapLocationAddress = addressStr;
       [self stopLoadingViewForView:self.view];
       
       if (self.chooseMapAddressBlock) {
           self.chooseMapAddressBlock(self.authModel);
       }
        [self.navigationController popViewControllerAnimated:YES];
    }];
}


-(void)configUI{
    
    
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:self.restaurantModel.latitude longitude:self.restaurantModel.longitude zoom:10];
    
    GMSMapView *mapView = [GMSMapView mapWithFrame:self.view.frame camera:camera];
    
    mapView.delegate = self;
    
    mapView.myLocationEnabled = YES;
    
    [self.view addSubview:mapView];
    
    GMSMarker *marker = [GMSMarker new];
    marker.position = CLLocationCoordinate2DMake(self.restaurantModel.latitude, self.restaurantModel.longitude);
    marker.icon = [UIImage imageNamed:@"map_location_icon_select"];
    marker.map = mapView;
    
    
    
    /*
     ==========================================annotation=================================================
     */
    self.calloutView = [SMCalloutView new];
    
    CustomAnnotationView *annotationView = [[CustomAnnotationView alloc]initWithTitle:self.restaurantModel.title detail:self.restaurantModel.content];
    
    [annotationView sizeToFit];
    
    self.calloutView.contentView = annotationView;
    self.calloutView.contentViewInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.emptyCalloutView = [UIView new];
    
}

#pragma
#pragma mark GMSMapViewDelegate
-(UIView *)mapView:(GMSMapView *)mapView markerInfoWindow:(GMSMarker *)marker{
    
    CLLocationCoordinate2D anchor = marker.position;
    CGPoint point = [mapView.projection pointForCoordinate:anchor];
    
    self.calloutView.calloutOffset = CGPointMake(0, -25);
    self.calloutView.hidden = NO;
    
    CGRect calloutRect = CGRectZero;
    calloutRect.origin = point;
    calloutRect.size = CGSizeZero;
    
    [self.calloutView presentCalloutFromRect:calloutRect
                                      inView:mapView
                           constrainedToView:mapView
                                    animated:YES];

    return self.emptyCalloutView;
}


- (void)mapView:(GMSMapView *)pMapView didChangeCameraPosition:(GMSCameraPosition *)position {
    /* move callout with map drag */
    if (pMapView.selectedMarker != nil && !self.calloutView.hidden) {
        CLLocationCoordinate2D anchor = [pMapView.selectedMarker position];
        
        CGPoint arrowPt = self.calloutView.backgroundView.arrowPoint;
        
        CGPoint pt = [pMapView.projection pointForCoordinate:anchor];
        pt.x -= arrowPt.x;
        pt.y -= arrowPt.y + 25;
        
        self.calloutView.frame = (CGRect) {.origin = pt, .size = self.calloutView.frame.size };
    } else {
        self.calloutView.hidden = YES;
    }
}


- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
    self.calloutView.hidden = YES;
    if (self.authModel) {//如果是商家认证, 展示选择的位置的标注
        self.chooseMarker.position = coordinate;
        self.chooseMarker.map = self.gmsMapView;
        self.chooseLat = coordinate.latitude;
        self.chooseLon = coordinate.longitude;
    }

}

- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
    mapView.selectedMarker = marker;
    return YES;
}




@end
